<template>
  <div id="homePage">
    <!-- 搜索框 -->
    <a-input-search
      class="search-bar"
      v-model:value="searchParams.searchText"
      placeholder="从平台中搜索"
      enter-button="搜索"
      size="large"
      @search="doSearch"
    />
    <!-- 分类和标签筛选 -->
    <!-- 分类 -->
    <a-tabs v-model:active-key="selectedCategory" @change="doSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :tab="category" :key="category" />
    </a-tabs>
    <!-- 标签 -->
    <div class="tag-bar">
      <span style="margin-right: 8px">标签:</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagsList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="doSearch"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>

    <!-- 图片列表 -->
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :pagination="pagination"
      :loading="loading"
    >
      <template #renderItem="{ item: picture }">
        <a-list-item  style="padding: 0">
          <!-- 单张图片 -->
          <a-card hoverable style="width: 240px" @click="doClickPicture(picture)">
            <template #cover>
              <img
                :alt="picture.name"
                :src="picture.url"
                style="height: 180px; object-fit: cover"
              />
            </template>
            <a-card-meta :title="picture.name">
              <template #description>
                <!-- 让每个标签之间有点距离(分类) -->
                <a-flex>
                  <a-tag color="green">{{ picture.category ?? '默认' }}</a-tag>
                  <a-tag v-for="tag in picture.tags" :key="tag">
                    {{ tag }}
                  </a-tag>
                </a-flex>
              </template>
            </a-card-meta>
          </a-card>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'

interface DataItem {
  title: string
}

const loading = ref(true)
const router = useRouter()

//定义数据
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)

//搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  pageNum: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

//获取数据
const fetchData = async () => {
  loading.value = true
  //转换搜索参数
  const params = { ...searchParams, tags: []}
  if(selectedCategory.value !== "all"){
    params.category = selectedCategory.value
  }
  //因为选中的时候组件使用布尔数组表示的，所以这里需要转换成字符数据
  selectedTagList.value.forEach((item, index) => {
    if (item) {
      params.tags.push(tagsList.value[index])
    }
  })
  //{ ...searchParams } 这里将 searchParams 的值展开传递到新的对象中，防止修改原对象被污染
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.code === 0 && res.data.data) {
    //?? 运算符用于处理可能为 null 或 undefined 的值，如果值为 null 或 undefined，则返回默认值，否则返回该值。
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败：' + res.data.message)
  }
  loading.value = false
}

//定义分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum,
    pageSize: searchParams.pageSize,
    total: total.value,
    //当分页参数发生变化时，会触发该事件，并更新分页参数。
    onChange: (page: number, pageSize: number) => {
      searchParams.pageNum = page
      searchParams.pageSize = pageSize
      fetchData()
    },
  }
})

//搜索函数
const doSearch = () => {
  //每次搜索都需要重置页码
  searchParams.pageNum = 1
  fetchData()
}
//获取标签和分类

const selectedCategory = ref<String>('all')
const categoryList = ref<String[]>([])
const selectedTagList = ref<boolean[]>([])
const tagsList = ref<String[]>([])

const getTagCategoryOptional = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    categoryList.value = res.data.data.categoryList ?? []
    tagsList.value = res.data.data.tagList ?? []
  } else {
    message.error('获取标签分类列表失败：' + res.data.message)
  }
}

const doClickPicture = (picture : API.PictureVO) => {
   router.push({
    path: `/picture/${picture.id}`,
  })
}

onMounted(() => {
  fetchData()
  getTagCategoryOptional()
})
</script>

<style scoped>
#homePage {
  margin: 20px;
}

.search-bar {
  max-width: 480px;
  margin: 0 auto 16px;
}

.tag-bar {
  margin-bottom: 16px;
}
</style>
